package org.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static org.example.Main.mocRequest;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class JMHMain {

    @Benchmark
    public void testRoutine100w() throws Exception {
        routine100w(1000000);
    }

    public void routine100w(int num) throws Exception {
        AtomicInteger count = new AtomicInteger(0);
        CountDownLatch wg = new CountDownLatch(num);
        ThreadFactory threadFactory = Thread.ofVirtual().inheritInheritableThreadLocals(true).factory();
        for (int i = 0; i < num; i++) {
            final int params = i;
            threadFactory.newThread(() -> {
                if (mocRequest(params) == params) {
                    count.addAndGet(1);
                    wg.countDown();
                }
            }).start();
        }
        wg.await();
        System.out.printf("100万routine从启动到执行结束，routine 执行的总次数：%d\n", count.get());
    }

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JMHMain.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}